<?php
session_start();
$lib_dir = str_ireplace("ajax", "lib", dirname(__FILE__));
require_once $lib_dir.'/config.php';
require_once $lib_dir.'/facebook.php';
require_once $lib_dir.'/util.php';
require_once $lib_dir.'/friends.php';

//if data is already loaded then reuse it
if(isset($_SESSION['friendsOfFriends'])){
    
    print($_SESSION['friendsOfFriends']);
    
} else {

    //check call validity
    if(!isset($_SESSION['fb_session']) && !isset($_REQUEST['signed_request']) ){
        print('{ "error": "Invalid request is detected. Program abort." }');
        exit();
    }
    
    //Init facebook instance
    $facebook = new Facebook(array(
        'appId' => FB_APP_ID,
        'secret' => FB_APP_SECRET
    ));
    
    if(isset($_SESSION['fb_session'])){
        $facebook->setSession($_SESSION['fb_session']);        
    }
    
    $session = $facebook->getSession();
    
    //data fetching
    $friendsOfFriends = null;
    if($session){
        try{
        $now = time();	
        	
            $friendsOfFriends = getFriendsOfFriends();
        error_log("Elapsed time for getFriends() : ".(time() - $now));
        $now = time();    

            //JSON encoding
            $_SESSION['progress'] = "JSON Encoding";
            $json = "[";
        
            $isFirst = true;
            foreach($friendsOfFriends as $f){
                if(!$isFirst){
                    $json .= ',';
                }
                $json .= '{';
                $json .= '"id1" : "'.$f['uid1'].'",';
                $json .= '"id2" : "'.$f['uid2'].'"';
                $json .= '}';
                $isFirst = false;
            }
        
            $json .= "]";
    
            $_SESSION['friendsOfFriends'] = $json;
            
            //return output
            print $json;
                
        } catch (FacebookApiException $e){
            error_log($e);
            print('{"error":"'."Facebook error:".$e->getMessage().'"}');
        }
    }
}